from web_driver.web_driver import GetDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from utils.record_log import LogConfig


class PageAbstract:
    """用于被所有页面继承的公共类"""

    # 自定义日志对象日志
    logger = LogConfig.get_config_logger()

    def __init__(self):
        self.driver = GetDriver.get_driver()

    def locate_ele_by_id(self, ele_value) -> WebElement:
        """
        通过id属性进行显式等待定位
        """
        return (
            WebDriverWait(self.driver, 10)
            .until(expected_conditions.visibility_of_element_located((By.ID, ele_value)),
                   "通过id定位该元素10s后查找失败")
        )

    def locate_ele_by_class_name(self, ele_value) -> WebElement:
        """
        通过class_name属性进行显式等待定位
        """
        return (
            WebDriverWait(self.driver, 5)
            .until(expected_conditions.visibility_of_element_located((By.CLASS_NAME, ele_value)),
                   "通过class_name定位该元素5s后查找失败")
        )

    def locate_ele_by_name(self, ele_value) -> WebElement:
        """
        通过name属性进行显式等待定位
        """
        return (
            WebDriverWait(self.driver, 5)
            .until(expected_conditions.visibility_of_element_located((By.NAME, ele_value)),
                   "通过name定位该元素5s后查找失败")
        )

    def locate_ele_by_link_text(self, ele_value) -> WebElement:
        """
        通过link_text进行显式等待定位
        """
        return (
            WebDriverWait(self.driver, 5)
            .until(expected_conditions.visibility_of_element_located((By.LINK_TEXT, ele_value)),
                   "通过link_text定位该元素5s后查找失败")
        )

    def locate_ele_by_css_selector(self, ele_value) -> WebElement:
        """
        通过css_selector进行显式等待定位
        """
        return (
            WebDriverWait(self.driver, 5)
            .until(expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, ele_value)),
                   "通过css_selector定位该元素5s后查找失败")
        )

    def locate_ele_by_xpath(self, ele_value) -> WebElement:
        """
        通过xpath进行显式等待定位
        """
        return (
            WebDriverWait(self.driver, 5)
            .until(expected_conditions.visibility_of_element_located((By.XPATH, ele_value)),
                   "通过xpath定位该元素5s后查找失败")
        )

    @classmethod
    def log_err(cls, msg, exception_msg):
        """
        记录错误日志、设置断言不通过
        :param msg: 错误提示信息
        :param exception_msg: 异常类具体信息
        """
        cls.logger.error(f"{msg} : ", exception_msg)
